﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Web.Security;
using System.Net.Mail;
using System.IO;

public partial class Users_CheckBill : System.Web.UI.Page
{
    TicketBAL _ticketBAL;
    protected void Page_Load(object sender, EventArgs e)
    {
        _ticketBAL = new TicketBAL();
        if (Session["DepartTicketList"] == null || Session["DepartRequestType"] == null)
        {
            Response.Redirect("~/Home.aspx");
        }
        string DepartRequest = Session["DepartRequestType"] as string;
        List<Ticket> DepartTicketList = (List<Ticket>)Session["DepartTicketList"];

        if (DepartRequest == "Buy")
        {
            string name = "Depart Flight<br />From : " + DepartTicketList[0].Flight.Route.Origin.FullName + " to : " + DepartTicketList[DepartTicketList.Count - 1].Flight.Route.Destination.FullName + "<br />" + DepartTicketList[0].Flight.DepartTime + "<br />Bill Detail";
            BuyTable table = new BuyTable(DepartTicketList, name, DepartTicketList[0].TicketDetail[0].SeatClass, _ticketBAL.getDiscount(DepartTicketList[0].Flight.DepartTime, "Buy"));
            PlaceHolder1.Controls.Add(table);
        }
        else if (DepartRequest == "Book")
        {
            string name = "Depart Flight<br />From : " + DepartTicketList[0].Flight.Route.Origin.FullName + " to : " + DepartTicketList[DepartTicketList.Count - 1].Flight.Route.Destination.FullName + "<br />" + DepartTicketList[0].Flight.DepartTime + "<br />Book Detail";
            BookTable table = new BookTable(DepartTicketList, name, DepartTicketList[0].TicketDetail[0].SeatClass);
            PlaceHolder1.Controls.Add(table);
        }

        if (Session["ReturnTicketList"] != null && Session["ReturnRequestType"] != null)
        {
            PlaceHolder2.Visible = true;
            string ReturnRequest = Session["ReturnRequestType"] as string;
            List<Ticket> ReturnTicketList = (List<Ticket>)Session["ReturnTicketList"];

            if (ReturnRequest == "Buy")
            {
                string name = "Return Flight<br />From : " + ReturnTicketList[0].Flight.Route.Origin.FullName + " to : " + ReturnTicketList[ReturnTicketList.Count - 1].Flight.Route.Destination.FullName + "<br />" + ReturnTicketList[0].Flight.DepartTime + "<br />Bill Detail";
                BuyTable table = new BuyTable(ReturnTicketList, name, ReturnTicketList[0].TicketDetail[0].SeatClass, _ticketBAL.getDiscount(ReturnTicketList[0].Flight.DepartTime, "Buy"));
                PlaceHolder2.Controls.Add(table);
            }
            else if (ReturnRequest == "Book")
            {
                string name = "Return Flight<br />From : " + ReturnTicketList[0].Flight.Route.Origin.FullName + " to : " + ReturnTicketList[ReturnTicketList.Count - 1].Flight.Route.Destination.FullName + "<br />" + ReturnTicketList[0].Flight.DepartTime + "<br />Book Detail";
                BookTable table = new BookTable(ReturnTicketList, name, ReturnTicketList[0].TicketDetail[0].SeatClass);
                PlaceHolder2.Controls.Add(table);
            }
        }

        ProfileCommon p = Profile.GetProfile(Membership.GetUser().UserName);
        lblCreditCard.Text = p.CreditCard.ToString().Substring(8);
    }

    private class BuyTable : Table
    {
        private int _totalPrice;
        public int TotalPrice
        {
            get { return _totalPrice; }
            set { _totalPrice = value; }
        }

        public BuyTable(List<Ticket> _ticketList, string name, string _seatClass, int _discount)
        {
            int baseprice = 0;
            #region get base price
            foreach (Ticket ticket in _ticketList)
            {
                if (_seatClass == "Bussiness")
                {
                    baseprice += ticket.Flight.BussPrice;
                }
                else if (_seatClass == "First")
                {
                    baseprice += ticket.Flight.FirstPrice;
                }
                else if (_seatClass == "Club")
                {
                    baseprice += ticket.Flight.ClubPrice;
                }
            }
            #endregion

            int numofAdult = 0;
            int priceofAdult = 0;
            int numofChild = 0;
            int priceofChild = 0;
            int numofSenior = 0;
            int priceofSenior = 0;
            foreach (Ticket ticket in _ticketList)
            {
                numofAdult = 0;
                numofChild = 0;
                numofSenior = 0;
                foreach (TicketDetail detail in ticket.TicketDetail)
                {
                    if (detail.Passenger.Age < 12)
                    #region child price
                    {
                        if (_seatClass == "Bussiness")
                        {
                            detail.Price = Convert.ToInt32(ticket.Flight.BussPrice - (ticket.Flight.BussPrice * (ticket.Flight.ChildDiscount + _discount) / 100));
                        }
                        else if (_seatClass == "First")
                        {
                            detail.Price = Convert.ToInt32(ticket.Flight.FirstPrice - (ticket.Flight.FirstPrice * (ticket.Flight.ChildDiscount + _discount) / 100));
                        }
                        else if (_seatClass == "Club")
                        {
                            detail.Price = Convert.ToInt32(ticket.Flight.ClubPrice - (ticket.Flight.ClubPrice * (ticket.Flight.ChildDiscount + _discount) / 100));
                        }
                        numofChild++;
                        priceofChild += detail.Price;
                    }
                    #endregion
                    else if (detail.Passenger.Age >= 65)
                    #region senior price
                    {
                        if (_seatClass == "Bussiness")
                        {
                            detail.Price = Convert.ToInt32(ticket.Flight.BussPrice - (ticket.Flight.BussPrice * (ticket.Flight.SeniorDiscount + _discount) / 100));
                        }
                        else if (_seatClass == "First")
                        {
                            detail.Price = Convert.ToInt32(ticket.Flight.FirstPrice - (ticket.Flight.FirstPrice * (ticket.Flight.SeniorDiscount + _discount) / 100));
                        }
                        else if (_seatClass == "Club")
                        {
                            detail.Price = Convert.ToInt32(ticket.Flight.ClubPrice - (ticket.Flight.ClubPrice * (ticket.Flight.SeniorDiscount + _discount) / 100));
                        }
                        numofSenior++;
                        priceofSenior += detail.Price;
                    }
                    #endregion
                    else
                    #region adult price
                    {
                        if (_seatClass == "Bussiness")
                        {
                            detail.Price = Convert.ToInt32(ticket.Flight.BussPrice - (ticket.Flight.BussPrice * _discount / 100));
                        }
                        else if (_seatClass == "First")
                        {
                            detail.Price = Convert.ToInt32(ticket.Flight.FirstPrice - (ticket.Flight.FirstPrice * _discount / 100));
                        }
                        else if (_seatClass == "Club")
                        {
                            detail.Price = Convert.ToInt32(ticket.Flight.ClubPrice - (ticket.Flight.ClubPrice * _discount / 100));
                        }
                        numofAdult++;
                        priceofAdult += detail.Price;
                    }
                    #endregion
                }
            }

            _totalPrice = numofAdult * priceofAdult + numofChild * priceofChild + numofSenior * priceofSenior;

            #region Row 1 header
            TableRow row1 = new TableRow();
            row1.Font.Bold = true;
            row1.BackColor = Color.AntiqueWhite;
            TableCell c1 = new TableCell();
            c1.ColumnSpan = 2;
            c1.Controls.Add(new LiteralControl(name));
            row1.Cells.Add(c1);
            #endregion
            this.Rows.Add(row1);

            #region Row 1.5 seat class
            TableRow row15 = new TableRow();
            TableCell c01 = new TableCell();
            c01.Controls.Add(new LiteralControl("Seat Class"));
            row15.Cells.Add(c01);
            TableCell c02 = new TableCell();
            c02.Controls.Add(new LiteralControl(_seatClass + " Class "));
            row15.Cells.Add(c02);
            #endregion
            this.Rows.Add(row15);

            #region Row 2 base price
            TableRow row2 = new TableRow();
            row2.BackColor = Color.Gray;
            row2.ForeColor = Color.White;

            TableCell c21 = new TableCell();
            c21.Controls.Add(new LiteralControl("Base Price"));
            row2.Controls.Add(c21);

            TableCell c22 = new TableCell();
            c22.Controls.Add(new LiteralControl(baseprice.ToString() + " USD"));
            row2.Cells.Add(c22);
            #endregion
            this.Rows.Add(row2);

            #region Row 2.5 Discount
            TableRow row25 = new TableRow();
            TableCell c251 = new TableCell();
            c251.Controls.Add(new LiteralControl("Discount"));
            row25.Cells.Add(c251);
            TableCell c252 = new TableCell();
            c252.Controls.Add(new LiteralControl(_discount + " % "));
            row25.Cells.Add(c252);
            #endregion
            this.Rows.Add(row25);

            #region Row 3 Adult Price
            TableRow row3 = new TableRow();

            TableCell c31 = new TableCell();
            c31.Controls.Add(new LiteralControl("Adult Price x " + numofAdult.ToString()));
            row3.Controls.Add(c31);

            TableCell c32 = new TableCell();
            c32.Controls.Add(new LiteralControl((priceofAdult * numofAdult).ToString() + " USD"));
            row3.Cells.Add(c32);
            #endregion
            this.Rows.Add(row3);

            #region Row 4 Child Price
            TableRow row4 = new TableRow();

            TableCell c41 = new TableCell();
            c41.Controls.Add(new LiteralControl("Child Price x " + numofChild.ToString() + " (with child discount)"));
            row4.Controls.Add(c41);

            TableCell c42 = new TableCell();
            c42.Controls.Add(new LiteralControl((priceofChild * numofChild).ToString() + " USD"));
            row4.Cells.Add(c42);
            #endregion
            this.Rows.Add(row4);

            #region Row 5 Senior Price
            TableRow row5 = new TableRow();

            TableCell c51 = new TableCell();
            c51.Controls.Add(new LiteralControl("Senior Price x " + numofSenior.ToString() + " (with senior discount)"));
            row5.Controls.Add(c51);

            TableCell c52 = new TableCell();
            c52.Controls.Add(new LiteralControl((priceofSenior * numofSenior).ToString() + " USD"));
            row5.Cells.Add(c52);
            #endregion
            this.Rows.Add(row5);

            #region Row 6 Total Price
            TableRow row6 = new TableRow();
            row6.BackColor = Color.LightBlue;
            row6.Font.Bold = true;

            TableCell c61 = new TableCell();
            c61.Controls.Add(new LiteralControl("Total Price"));
            row6.Controls.Add(c61);

            TableCell c62 = new TableCell();
            c62.Controls.Add(new LiteralControl(_totalPrice.ToString() + " USD"));
            row6.Cells.Add(c62);
            #endregion
            this.Rows.Add(row6);

            this.Width = Unit.Percentage(100);
            this.Font.Size = FontUnit.Large;
        }
    }

    private class BookTable : Table
    {
        public BookTable(List<Ticket> _ticketList, string name, string _seatClass)
        {
            int numofAdult = 0;
            int numofChild = 0;
            int numofSenior = 0;

            foreach (TicketDetail detail in _ticketList[0].TicketDetail)
            {
                if (detail.Passenger.Age < 12)
                #region num of child
                {
                    numofChild++;
                }
                #endregion
                else if (detail.Passenger.Age >= 65)
                #region num of senior
                {

                    numofSenior++;
                }
                #endregion
                else
                #region num of adult
                {
                    numofAdult++;
                }
                #endregion
            }

            #region Row 1 header
            TableRow row1 = new TableRow();
            row1.Font.Bold = true;
            row1.BackColor = Color.AntiqueWhite;
            TableCell c1 = new TableCell();
            c1.ColumnSpan = 2;
            c1.Controls.Add(new LiteralControl(name));
            row1.Cells.Add(c1);
            #endregion
            this.Rows.Add(row1);

            #region Row 1.5 seat class
            TableRow row15 = new TableRow();
            TableCell c01 = new TableCell();
            c01.Controls.Add(new LiteralControl("Seat Class"));
            row15.Cells.Add(c01);
            TableCell c02 = new TableCell();
            c02.Controls.Add(new LiteralControl(_seatClass + " Class"));
            row15.Cells.Add(c02);
            #endregion
            this.Rows.Add(row15);

            #region Row 3 Num of Adult
            TableRow row3 = new TableRow();

            TableCell c31 = new TableCell();
            c31.Controls.Add(new LiteralControl("Adult"));
            row3.Controls.Add(c31);

            TableCell c32 = new TableCell();
            c32.Controls.Add(new LiteralControl(numofAdult.ToString() + " Seat(s)"));
            row3.Cells.Add(c32);
            #endregion
            this.Rows.Add(row3);

            #region Row 4 Num of Child
            TableRow row4 = new TableRow();

            TableCell c41 = new TableCell();
            c41.Controls.Add(new LiteralControl("Child"));
            row4.Controls.Add(c41);

            TableCell c42 = new TableCell();
            c42.Controls.Add(new LiteralControl(numofChild.ToString() + " Seat(s)"));
            row4.Cells.Add(c42);
            #endregion
            this.Rows.Add(row4);

            #region Row 5 Num of Senior
            TableRow row5 = new TableRow();

            TableCell c51 = new TableCell();
            c51.Controls.Add(new LiteralControl("Senior"));
            row5.Controls.Add(c51);

            TableCell c52 = new TableCell();
            c52.Controls.Add(new LiteralControl(numofSenior.ToString() + " Seat(s)"));
            row5.Cells.Add(c52);
            #endregion
            this.Rows.Add(row5);

            this.Width = Unit.Percentage(100);
            this.Font.Size = FontUnit.Large;
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {

        //Update database
        string userid = Membership.GetUser().ProviderUserKey.ToString();
        string Departrequest = Session["DepartRequestType"] as string;
        List<Ticket> DepartTicketList = Session["DepartTicketList"] as List<Ticket>;
        double distance;
        List<double> departticketIDs = _ticketBAL.NewTicket(DepartTicketList, Departrequest, userid);
        List<double> returnticketIDs = new List<double>();
        distance = departticketIDs[departticketIDs.Count - 1];
        departticketIDs.RemoveAt(departticketIDs.Count - 1);
        if (Departrequest == "Buy")
        {
            ProfileCommon p = Profile.GetProfile(Membership.GetUser().UserName);
            p.SkyMeter += distance;
            p.Save();
        }

        if (Session["ReturnTicketList"] != null && Session["ReturnRequestType"] != null)
        {
            string Returnrequest = Session["ReturnRequestType"] as string;
            List<Ticket> ReturnTicketList = Session["ReturnTicketList"] as List<Ticket>;
            returnticketIDs = _ticketBAL.NewTicket(ReturnTicketList, Returnrequest, userid);
            distance = returnticketIDs[returnticketIDs.Count - 1];
            returnticketIDs.RemoveAt(returnticketIDs.Count - 1);

            if (Returnrequest == "Buy")
            {
                ProfileCommon p = Profile.GetProfile(Membership.GetUser().UserName);
                p.SkyMeter += distance;
                p.Save();
            }
        }

        //Send mail
        string mailbodytemplate = Server.MapPath("~/MailTemplate/NewTicket.txt");
        string username = Membership.GetUser().UserName;
        string email = Membership.GetUser().Email;

        SmtpClient client;
        client = new SmtpClient("smtp.gmail.com", 587);
        client.EnableSsl = true;
        MailMessage message;
        message = new MailMessage();
        message.From = new MailAddress("anhvhb00319@gmail.com", "Airline Reservation Team");
        message.IsBodyHtml = false;
        message.To.Clear();
        message.To.Add(new MailAddress(email));
        message.Subject = "New Ticket";
        message.Body = File.OpenText(mailbodytemplate).ReadToEnd();

        message.Body = message.Body.Replace("<%UserName%>", username);
        message.Body = message.Body.Replace("<%Origin%>", DepartTicketList[0].Flight.Route.Origin.FullName);
        message.Body = message.Body.Replace("<%Destination%>", DepartTicketList[DepartTicketList.Count - 1].Flight.Route.Destination.FullName);
        message.Body = message.Body.Replace("<%DepartTime%>", DepartTicketList[0].Flight.DepartTime.ToString("hh:mm tt dddd dd - MMM - yyyy"));
        string departid = "Depart tickets' id : ";
        foreach (double item in departticketIDs)
        {
            departid += item.ToString() + ",";
        }
        message.Body = message.Body.Replace("<%departticketid%>", departid);
        if (Session["ReturnTicketList"] != null && Session["ReturnRequestType"] != null)
        {
            message.Body = message.Body.Replace("<%ways%>", "2-ways");
            string returnid = "Retrun tickets' id : ";
            foreach (double item in returnticketIDs)
            {
                returnid += item.ToString() + ",";
            }
            message.Body = message.Body.Replace("<%returnticketid%>", returnid);
            List<Ticket> ReturnTicketList = Session["ReturnTicketList"] as List<Ticket>;
            message.Body = message.Body.Replace("<%ReturnTime%>", "Return flight will take off at " + ReturnTicketList[0].Flight.DepartTime.ToString("hh:mm tt dddd dd - MMM - yyyy") + ".");
        }
        else
        {
            message.Body = message.Body.Replace("<%ways%>", "one-way");
            message.Body = message.Body.Replace("<%returnticketid%>", "");
            message.Body = message.Body.Replace("<%ReturnTime%>", "");
        }


        client.Send(message);

        //Confirm
        MultiView1.ActiveViewIndex = 1;
        lblComplete.Text = "Buy/Book Ticket complete.<br />For booked ticket, you must confirm 2 weeks before the depart time or it will expried.";


        Session.Remove("origin");
        Session.Remove("destination");

        Session.Remove("DepartRoute");
        Session.Remove("DepartDates");
        Session.Remove("ReturnRoute");
        Session.Remove("ReturnDates");
        Session.Remove("bigFlightListDepart");
        Session.Remove("bigFlightListReturn");

        Session.Remove("Adult");
        Session.Remove("Child");
        Session.Remove("Senior");

        Session.Remove("DepartRequestType");
        Session.Remove("ReturnRequestType");
        Session.Remove("DepartTicketList");
        Session.Remove("ReturnTicketList");
        PlaceHolder3.Visible = false;
    }
}
